package com.bwie.groupon.controller;

import java.math.BigDecimal;
import java.util.Arrays;
import java.util.Date;
import java.util.Map;


import com.alibaba.csp.sentinel.Entry;
import com.alibaba.csp.sentinel.SphU;
import com.alibaba.csp.sentinel.annotation.SentinelResource;
import com.alibaba.csp.sentinel.slots.block.BlockException;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.bwie.groupon.entity.GrouponDescEntity;
import com.bwie.groupon.feign.HouseFeignService;
import com.bwie.groupon.feign.UserFeignService;
import com.bwie.groupon.service.GrouponDescService;
import com.bwie.groupon.to.FlatsTo;
import com.bwie.groupon.to.UserTo;
import io.seata.spring.annotation.GlobalTransactional;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import com.bwie.groupon.entity.GrouponEntity;
import com.bwie.groupon.service.GrouponService;
import com.bwie.common.utils.PageUtils;
import com.bwie.common.utils.R;



/**
 * 
 *
 * @author wangguohai
 * @email 270901876@qq.com
 * @date 2022-04-26 19:40:24
 */
@Slf4j
@RestController
@RequestMapping("groupon/groupon")
public class GrouponController {
    @Autowired
    private GrouponService grouponService;

    @Autowired
    private HouseFeignService houseFeignService;



    @Autowired
    private UserFeignService userFeignService;

    @Autowired
    private GrouponDescService grouponDescService;

    @Autowired
    private RabbitTemplate rabbitTemplate;

    @GetMapping("/test")
    public String createOrderTest(){
        GrouponEntity grouponEntity = new GrouponEntity();
        grouponEntity.setFlatsName("111");


        //给mq发送消息
        rabbitTemplate.convertAndSend("order-event-exchange","order.create.order",grouponEntity);
        return "ok";

    }


    /**
     * 列表
     */
    @RequestMapping("/list")
    public R list(@RequestParam Map<String, Object> params){
        PageUtils page = grouponService.queryPage(params);

        return R.ok().put("page", page);
    }


    /**
    * @Author: 龍
    * @Description: 开团
    * @DateTime: 2022/4/29 19:01
    * @Params:
    * @Return
    */
    @RequestMapping("/group/{grouponId}")
    public R mygroup(@PathVariable("grouponId")Integer grouponId){
        return grouponService.mygroup(grouponId);
    }



    public R blockHandler(Integer grouponId,Integer userId,BlockException e){

        log.error("organizationResource被降级了。。。。。。。");
        return new R();

    }

    /**
     * #Description 入团逻辑
     * @param  * @param grouponId
     * @param userId
     * @return R
     * @author 王国海
     * #Date 2022/4/28
     */
    @GlobalTransactional
    @Transactional
    @SentinelResource(value = "organizationResource",blockHandler ="blockHandler" )
    @RequestMapping("/organization/{grouponId}/{userId}")
    public R organization(@PathVariable("grouponId")Integer grouponId,@PathVariable("userId")Integer userId){

        //判断时间  是否是在一个开团的状态
        GrouponEntity grouponEntity = grouponService.getById(grouponId);
        Date date = new Date();
        Integer groupStatus = grouponEntity.getGroupStatus();
        Date startTime = grouponEntity.getStartTime();
        Date endTime = grouponEntity.getEndTime();

        if (groupStatus==1&&date.getTime()<endTime.getTime()&&date.getTime()>startTime.getTime()){
            //判断我们是否已经入团

            GrouponDescEntity grouponDescEntity = grouponDescService.selectByUserId(userId);

            if (grouponDescEntity==null){
                //可以正常的入团

                try(Entry entry=SphU.entry("skill")) {
                    //查询用户信息
                    UserTo userTo= userFeignService.getUserById(userId);

                    //查询楼盘信息
                    Integer flatsId = grouponEntity.getFlatsId();
                    FlatsTo flatsTo=houseFeignService.getHouse(flatsId);

                    GrouponDescEntity grouponDesc = new GrouponDescEntity();
               /* if (flatsTo==null || userTo!=null){
                    throw new RuntimeException("运行时异常");
                }*/
                    grouponDesc.setUserId(userId);
                    grouponDesc.setGrouponId(grouponId);
                    grouponDesc.setUserName(userTo.getUname());
                    grouponDesc.setJoinTime(new Date());
                    grouponDesc.setUnitId(flatsTo.getUnitId());
                    grouponDesc.setStatus(0);
                    grouponDesc.setPhone(userTo.getMobile());
                    grouponDesc.setUnitName("三室两厅两卫");
                    grouponDesc.setUnitId(flatsTo.getUnitId());
                    grouponDesc.setSubscription(new BigDecimal("0"));

                    grouponDescService.save(grouponDesc);

                    grouponEntity.setPeopleCount(grouponEntity.getPeopleCount()+1);
                    grouponService.updateById(grouponEntity);

                }catch (BlockException e){
                    log.info("资源被限流了。。。。。。");
                }

            }else {
                return R.error().put("msg","已加入团购");
            }
        }else {
            return R.error().put("msg","团购未开始或团购已结束");
        }

        return R.ok().put("msg","入团成功");
    }


    /**
     * #Description 退团逻辑
     * @param  * @param grouponId
     * @param userId
     * @return R
     * @author 王国海
     * #Date 2022/4/28
     */
    @RequestMapping("/quit/{grouponId}/{userId}")
    public R quit(@PathVariable("grouponId")Integer grouponId,@PathVariable("userId")Integer userId){

        Date date = new Date();
        QueryWrapper<GrouponDescEntity> wrapper = new QueryWrapper<>();
        wrapper.eq("groupon_id",grouponId);
        wrapper.eq("user_id",userId);
        GrouponDescEntity one = grouponDescService.getOne(wrapper);
        Date joinTime = one.getJoinTime();
        System.out.println(joinTime);
        joinTime.setDate(joinTime.getDate()+3);
        //当前人数减一
        GrouponEntity byId = grouponService.getById(grouponId);
        byId.setPeopleCount(byId.getPeopleCount()-1);
        grouponService.updateById(byId);

        //删除记录
        grouponDescService.removeById(one.getGrouponDescId());
        //超过超过三天了
        if (date.getTime()>joinTime.getTime()){
            return R.ok().put("msg","已经退出,需要支付200元的后悔金");
        }else {
            //没有过三天，无条件退出

            return R.ok().put("msg","已经退出，无需交付任何费用");
        }
    }


    /**
    * @Author: 龍
    * @Description: 我的团购
    * @DateTime: 2022/4/29 18:59
    * @Params: openGroupPeopleId
    * @Return R
    */
    @RequestMapping("/myList/{openGroupPeopleId}")
    public R myList(@PathVariable("openGroupPeopleId") Integer openGroupPeopleId){
        return grouponService.myLists(openGroupPeopleId);
    }



    /**
     * 信息
     */
    @RequestMapping("/info/{grouponId}")
    public R info(@PathVariable("grouponId") Integer grouponId){
		GrouponEntity groupon = grouponService.getById(grouponId);

        return R.ok().put("groupon", groupon);
    }

    /**
     * 保存
     */
    @RequestMapping("/save")
    public R save(@RequestBody GrouponEntity groupon){
		grouponService.save(groupon);

        return R.ok();
    }

    /**
     * 修改
     */
    @RequestMapping("/update")
    public R update(@RequestBody GrouponEntity groupon){
		grouponService.updateById(groupon);

        return R.ok();
    }

    /**
     * 删除
     */
    @RequestMapping("/delete")
    public R delete(@RequestBody Integer[] grouponIds){
		grouponService.removeByIds(Arrays.asList(grouponIds));

        return R.ok();
    }

}
